package com.github.browep.bat.util;

import android.app.Activity;
import android.test.ActivityUnitTestCase;
import com.github.browep.bat.activities.Home;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.IOException;
import java.io.InputStream;

import static com.github.browep.bat.util.XmlUtil.*;

/**
 * Created by IntelliJ IDEA.
 * User: paul
 * Date: 8/26/11
 * Time: 4:52 PM
 * To change this template use File | Settings | File Templates.
 */
public class TestXmlUtil extends ActivityUnitTestCase<Home> {

    private DocumentBuilderFactory dbf;
    private DocumentBuilder db;

    public TestXmlUtil() {
        super(Home.class);
    }

    Activity mActivity;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        mActivity = this.getActivity();

        dbf = DocumentBuilderFactory.newInstance();
        db = dbf.newDocumentBuilder();

    }

    public void testGetSingleElement() throws Exception {

        InputStream inputStream = getInstrumentation().getContext().getAssets().open("simple_1.xml");
        Document document = db.parse(inputStream);
        Element rootElement = document.getDocumentElement();
        assertNotNull(getElementByTagName(rootElement, "sub-1"));

        inputStream = getInstrumentation().getContext().getAssets().open("simple_data_2.xml");
        document = db.parse(inputStream);
        rootElement = document.getDocumentElement();
        try {
            assertNotNull(getElementByTagName(rootElement, "sub-1"));
            assertTrue("should never get here",false);
        } catch (Exception e) {
            assertEquals(e.getClass(),IllegalArgumentException.class);
        }
    }

    public void testGetElementByTagAndId() throws Exception {

        Element rootElement = getRootFromFileName("simple_data_3.xml");
        assertNotNull(getElementByTagAndId(rootElement, "sub-1","foo"));
        assertNull(getElementByTagAndId(rootElement, "sub-2", "foo"));
        assertNotNull(getElementByTagAndId(rootElement, "sub-1", "bar"));

    }

    private Element getRootFromFileName(String fileName) throws IOException, SAXException {
        InputStream inputStream = getInstrumentation().getContext().getAssets().open(fileName);
        Document document = db.parse(inputStream);
        return document.getDocumentElement();
    }

    public void testGetChildElementListWithTag() throws Exception {
        Element rootElement = getRootFromFileName("simple_data_4.xml");
        assertEquals(3,getChildElementListWithTag(rootElement,"sub-1").size());
        assertEquals(2,getChildElementListWithTag(rootElement,"sub-2").size());
        assertEquals(0,getChildElementListWithTag(rootElement,"foo").size());

    }

}
